package com.cocos.game;


import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;


import com.android.matchmagicv2.tripletitles.BuildConfig;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


public class NetHelper {
    private static final int TIMEOUT = 20;
    private static volatile NetHelper instance;
    private static OkHttpClient okHttpClient;


    public static NetHelper getInstance() {
        if (instance == null) {
            synchronized (NetHelper.class) {
                if (instance == null) {
                    instance = new NetHelper();
                }
            }
        }
        return instance;
    }

    private NetHelper() {
        okHttpClient = getClient(createLoggingInterceptor());
    }

    private OkHttpClient getClient(Interceptor... interceptor) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS);
        for (Interceptor anInterceptor : interceptor) {
            builder.addInterceptor(anInterceptor);
        }
        return builder.build();
    }

    private static Interceptor createLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    public void logReport(String eventName, Map<String, String> params) {
        StringBuilder urlBuilder = new StringBuilder("http://as.33t8y678tyy6rt.top/admin_bi/data/syncEventData");
        urlBuilder.append("?");

        for (String key : params.keySet()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                urlBuilder.append(key).append("=").append(URLEncoder.encode(params.get(key), StandardCharsets.UTF_8)).append("&");
            } else {
                try {
                    urlBuilder.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }

        // 创建请求
        Request request = new Request.Builder()
                .url(urlBuilder.toString())
                .get()
                .build();
        // 定义重试策略
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, 1000); // 最多重试3次，每次间隔1秒

        // 执行请求
        executeRequestWithRetry(request, retryPolicy, eventName, params, 0);
    }

    private void executeRequestWithRetry(Request request, SimpleRetryPolicy retryPolicy, String eventName, Map<String, String> params, int currentRetryCount) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d("LogReport", "上报服务器 成功 event=" + eventName + " params=" + params);
                // 关闭响应体
                if (response.body() != null) {
                    response.body().close();
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                if (retryPolicy.shouldRetry(currentRetryCount)) {
                    // 计算下一次重试的延迟时间
                    long delay = retryPolicy.getRetryDelayMillis(currentRetryCount);

                    // 休眠一段时间后重新发送请求
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        executeRequestWithRetry(request, retryPolicy, eventName, params, currentRetryCount + 1);
                    }, delay);
                } else {
                    Log.d("LogReport", "上报服务器 失败 event=" + eventName + " params=" + params);
                }
            }
        });
    }

    public static class SimpleRetryPolicy {
        private final int maxRetries;
        private final long retryDelayMillis;

        public SimpleRetryPolicy(int maxRetries, long retryDelayMillis) {
            this.maxRetries = maxRetries;
            this.retryDelayMillis = retryDelayMillis;
        }

        public boolean shouldRetry(int currentRetryCount) {
            return currentRetryCount < maxRetries;
        }

        public long getRetryDelayMillis(int currentRetryCount) {
            return retryDelayMillis;
        }
    }

}
